import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import { UserState } from '@/stores/modules/types/types'
import type { loginFormData, loginResponseData } from '@/api/user/type'
import {MessagePlugin, NotifyPlugin} from 'tdesign-vue-next';
export const useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      token: localStorage.getItem('token') || '',
      username: '1472939313',
      nickName:'',
      // avatar: 'https://p3-pc-sign.douyinpic.com/aweme-avatar/tos-cn-i-0813_3b226974f58e47a9ae339c5e4af1363c~tplv-8yspqt5zfm-300x300.webp?lk3s=93de098e&x-expires=1743483600&x-signature=z9U7TTvGROmcsgzF7DwQ5ItwtHs%3D&from=2480802190&s=profile&se=false&sc=avatar&l=20250330132345492E594C003F98F5C80A',
      avatar: '',
      userId: '',
      tel:'15065606797',
      guanZhuNumber:0,
      likedNumber:0,
      fenSiNumber:0
    }
  },
  actions: {
    async login(data: loginFormData) {
      const res: loginResponseData = await reqLogin(data)
      if (res.code === 200) {
        this.token = res.data
        localStorage.setItem('token', res.data)
        return 'ok'
      } else {
        return Promise.reject(new Error(res.msg))
      }
    },
    async userInfo() {
      const res = await reqUserInfo(this.token)
      if (res.code === 200) {
        const { userName,phone, name, avatar ,userId,guanZhuNumber,fenSiNumber , likedNumber } = res.data
        this.nickName = name
        this.fenSiNumber = fenSiNumber
        this.guanZhuNumber = guanZhuNumber
        this.likedNumber = likedNumber
        this.tel = phone
        this.username = userName
        if (avatar.startsWith('https')) {
          this.avatar = avatar
        } else {
          this.avatar = '/api' + avatar
        }
        this.userId = userId
        return this.role;
      } else {

        return Promise.reject(new Error(res.msg))
      }
    },
    mockData(){
      this.userInfo.token = 1
    },
    async logout() {
      this.username = ''
      this.avatar = ''
      this.role = ''
      this.token = ''
      this.name = ''
      localStorage.removeItem('token')
      MessagePlugin.success({content:'退出登录成功~'})
      return 'ok'

    },
  },
  getters: {},
})
